<?php
namespace app\shop\controller;

use app\common\model\shop\CategoryModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;

/**
 * 分类管理
 * @package app\shop\controller
 * @author xuli
 * @DateTime 2024-10-25 09:50
 */
class Category extends Controller
{
    /**
     * 分类列表
     * @auth true
     * @menu true
     * @author xuli
     * @DateTime 2024-10-25 09:50
     * @return void
     */
    public function index()
    {
        CategoryModel::mQuery()->layTable(function () {
            $this->title = lang('分类管理');

        }, function (QueryHelper $query) {
            $pid = $this->request->param('pid', 0);
            $query->where(['pid' => $pid, 'status' => 1]);
            // 数据列表搜索过滤
            $query->like('name')->equal('pid,status')->dateBetween('create_at');
        });
    }

    protected function _index_page_filter(&$data)
    {

    }

    /**
     * 添加
     * @auth true
     * @menu true
     * @author xuli
     * @DateTime 2024-10-25 09:50
     * @return void
     */
    public function add()
    {
        CategoryModel::mForm();
    }

    /**
     * 编辑
     * @auth true
     * @menu true
     * @author xuli
     * @DateTime 2024-10-25 09:50
     * @return void
     */
    public function edit()
    {
        CategoryModel::mForm();
    }

    protected function _form_filter(&$data)
    {
        $params = $this->request->param();
        if($this->request->isPost()) {
            // 获取父级分类信息
            if($params['pid']) {
                $parent_info = CategoryModel::mk()->find($params['pid']);
                if(!$parent_info) {
                    $this->error(lang('父级分类信息错误'));
                }
                $path = $parent_info['path'] . '/' . $params['pid'];
                $level = $parent_info['level'] + 1;
            } else {
                $path = '0';
                $level = 1;
            }

            // 验证
            $this->_vali([
                'name.require'       => lang('分类名称不能为空'),
                'name.length:1,100'  => lang('分类名称长度不能超过100'),
                'code.require'       => lang('分类编码不能为空'),
                'account_id.require' => lang('公司不能为空'),
            ]);

            $data = [
                'pid' => $params['pid'],
                'name' => $params['name'],
                'user_id' => $this->adminUser['id'],
                'account_id' => $params['account_id'] ?? 0,
                'level' => $level,
                'code' => $params['code'] ?? '',
                'remark' => $params['remark'] ?? '',
                'path' => $path,
            ];

            if(empty($params['id'])) { // 添加
                // 检查分类编码是否重复
                $info = CategoryModel::mk()->where(['account_id' => $this->adminUser['account_id'], 'code' => $params['code']])->find();
                if($info) {
                    $this->error(lang('分类编码重复，保存失败'));
                }
                $result = CategoryModel::mk()->insertGetId($data);
            } else { // 编辑
                // 检查分类编码是否重复
                $info = CategoryModel::mk()->where(['account_id' => $this->adminUser['account_id'], 'code' => $params['code']])->whereNotIn('id', $params['id'])->find();
                if($info) {
                    $this->error(lang('分类编码重复，保存失败'));
                }
                $result = CategoryModel::mk()->where(['id' => $params['id']])->update($data);
            }

            if($result) {
                $this->success(lang('保存成功'));
            } else {
                $this->error(lang('保存失败'));
            }
        } else {
            $this->pid = $params['pid'] ?? 0;
            $this->parent_info = CategoryModel::mk()->find($this->pid);
            if(!empty($params['id'])) { // 添加分类或者子集
                $this->info = CategoryModel::mk()->find($params['id']);
                $this->id = $params['id'];
            }
            $this->shop_account = !empty($data['account_id']) ? $data['account_id'] : $this->account_id;
        }
    }

    /**
     * 删除
     * @auth true
     * @menu true
     * @return void
     */
    public function delete()
    {
        $id = $this->request->param('id', 0);
        $info = CategoryModel::mk()->find($id);
        if(!$info) {
            $this->error('分类信息错误');
        }
        try {
            $result = CategoryModel::where(['id' => $id])->delete();
            if(!$result){
                throw new \Exception(lang('删除失败'));
            }
        } catch (\Exception $e) {
            $this->error(lang('删除失败'));
        }
        $this->success(lang('删除成功'));
    }

    /**
     * 获取分类树
     * @return void
     */
    function getCategoryTree()
    {
        $search_key = $this->request->param('search_key', '');
        $where = [
            ['status', '=', 1],
        ];
        if(!empty($search_key)) {
            $where[] = ['name', 'like', '%'.$search_key.'%'];
        }
        $list = CategoryModel::mk()->where($where)->order('level')->field('name title,id,pid,path')->select()->toArray();
        $ids = [];
        foreach ($list as $k => $v) {
            $ids[] = $v['pid'];
        }
        $is_expand = 0;
        $whereOr = [
            ['id', 'in', $ids],
            ['name', 'like', '%'.$search_key.'%'],
        ];
        if(!empty($search_key)) {
            $list = CategoryModel::mk()->field('name title,id,pid,path')->where(function($query) use ($whereOr) {
                $query->whereOr($whereOr);
            })->order('level')->select()->toArray();
            $is_expand = 1;
        }
        $list = CategoryModel::categoryTree($list, $is_expand);
        // 处理分类树
        $this->success('分类树列表', ['list' => $list]);
    }

}